package com.huawei.basic.utils;

import com.huawei.basic.jwt.JwtUtils;
import com.huawei.basic.jwt.LoginSuccessObj;
import com.huawei.basic.jwt.Payload;
import com.huawei.basic.jwt.RsaUtils;
import com.huawei.user.domain.Logininfo;
import com.huawei.basic.jwt.JwtUtils;
import com.huawei.basic.jwt.LoginSuccessObj;
import com.huawei.basic.jwt.Payload;
import com.huawei.basic.jwt.RsaUtils;
import com.huawei.user.domain.Logininfo;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 登录上下文
 * 登录相关的信息
 *  1.获取当前登录人
 *  2.获取当前登录人所拥有的权限
 */
public class LoginContext {

    /**
     * 获取当前登录人
     * @param request
     * @return
     */
    public static Logininfo getCurrentLoginInfo(HttpServletRequest request){
        //1.获取jwt
        String jwtStr = request.getHeader("U-TOKEN");
        //1.1 jwt没值 return null;//降级方案
        if(StringUtils.isEmpty(jwtStr)){
            return null;
        }
        //1.2有值
        //2.解密JWT 得到LoginSuccessObj
        //2.解密JWT串
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<LoginSuccessObj> payload = JwtUtils.getInfoFromToken(jwtStr, publicKey, LoginSuccessObj.class);
            LoginSuccessObj loginSuccessObj = (LoginSuccessObj)payload.getUserInfo();//LoginSuccessObj
            //3.取出Logininfo返回
            return loginSuccessObj.getLogininfo();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
